﻿using CashFlow.Db.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1._02_Common
{
    public class UserRelationShipTool
    {
        public static IList<UserInfoEntity> GetAllChildUsers(UserInfoEntity userInfo
            , IList<UserInfoEntity> users)
        {
            var ls = new List<UserInfoEntity>();
            ls.Add(userInfo);

            var queue = new Queue<string>();
            queue.Enqueue(userInfo.InvitationCode);
            while (queue.Count > 0)
            {
                string code = queue.Dequeue();
                var ls2 = users.Where(x => x.ReferenceInvitationCode == code).ToList();
                foreach (var item2 in ls2)
                {
                    ls.Add(item2);
                    queue.Enqueue(item2.InvitationCode);
                }
            }

            return ls;
        }

        public static IList<int> GetAllChildUserIds(UserInfoEntity userInfo
            , IList<UserInfoEntity> users)
        {
            var ls = GetAllChildUsers(userInfo, users).Select(x => x.Id).ToList();
            return ls;
        }

        public static IList<UserInfoEntity> GetShopAllChildUsers(UserInfoEntity userInfo
            , IList<UserInfoEntity> users
            , IList<ShopUserEntity> shopUsers)
        {
            var ls = new List<UserInfoEntity>();
            ls.Add(userInfo);

            var shopUserIds = shopUsers.Select(x => x.UserId).ToList();
            var queue = new Queue<string>();
            queue.Enqueue(userInfo.InvitationCode);
            while (queue.Count > 0)
            {
                string code = queue.Dequeue();
                var ls2 = users.Where(x => x.ReferenceInvitationCode == code).ToList();
                foreach (var item2 in ls2)
                {
                    if (shopUserIds.Contains(item2.Id))
                    {
                        ls.Add(item2);
                        queue.Enqueue(item2.InvitationCode);
                    }
                }
            }

            return ls;
        }

        public static IList<int> GetShopAllChildUserIds(UserInfoEntity userInfo
            , IList<UserInfoEntity> users
            , IList<ShopUserEntity> shopUsers)
        {
            var ls = GetShopAllChildUsers(userInfo, users, shopUsers).Select(x => x.Id).ToList();
            return ls;
        }
    }
}
